# author: Jochen Rehmert, University of Basel
# journal: Journal of Politics
# article: Intra-party competition, geographic responsiveness 
#           and incumbent deselection in closed-list PR
# date: 12th August 2024
# content: Script to replicate Figures 2, 3, 6, 7, 8, 9 in the main text & Appendix
# needs data: "cj_1.RDS"
# see also: "data_description_cj_1.txt"

# directory: 
setwd("")

sink("log_rep_figure2_3_6_7_8_9.txt")
cat("start logging\n")

dat <- readRDS("cj_1.RDS")


##############################
# Analysis Preparation
##############################
# formula
f1 <- choice ~ cj_age + cj_sex + cj_wk + cj_ideo + cj_born  + cj_interest + cj_tenure + cj_loyalty

library(cregg)

# calculate ideological position of delegate relative to party
# lower values are left-wing, higher values right-wing delegates
dat$ideol_leaning <- dat$ideology_own - dat$ideology_pty

# categorization of ideology for matching below
dat$ideol_cat <- as.character(NA)
dat$ideol_cat[ dat$ideol_leaning > 3  ] <- "Right-wing" 
dat$ideol_cat[ dat$ideol_leaning < -3  ] <- "Left-wing" 
dat$ideol_cat[ dat$ideol_leaning < 3 & dat$ideol_leaning > -3 ] <- "Centrist" 
dat$ideol_cat_f <- factor(dat$ideol_cat)

# create indicator of ideological proximity
dat$cj_same_ideology <- 0
dat$cj_same_ideology[dat$cj_ideo == "Left-wing" & dat$ideol_leaning < -3] <- 1
dat$cj_same_ideology[dat$cj_ideo == "Right-wing" & dat$ideol_leaning > 3] <- 1
dat$cj_same_ideology[dat$cj_ideo == "Centrist" & (dat$ideol_leaning < 3 & dat$ideol_leaning > -3)] <- 1
dat$cj_same_ideology[is.na(dat$ideol_leaning) ] <- NA
# turn into factor
dat$cj_same_ideology <- as.factor(dat$cj_same_ideology)

dat.cdu <- dat[dat$party == "CDU",]
dat.spd <- dat[dat$party == "SPD",]
dat.fdp <- dat[dat$party == "FDP",]
dat.b90 <- dat[dat$party == "B90/Grüne",]
dat.linke <- dat[dat$party == "LINKE",]


dat.pr <- dat[dat$party %in% c("FDP", "LINK","B90/Grüne"),]

dat.cdu <- dat.cdu[!is.na(dat.cdu$ResponseId),]
dat.spd <- dat.spd[!is.na(dat.spd$ResponseId),]
dat.fdp <- dat.fdp[!is.na(dat.fdp$ResponseId),]
dat.b90 <- dat.b90[!is.na(dat.b90$ResponseId),]
dat.linke <- dat.linke[!is.na(dat.linke$ResponseId),]
dat.pr <- dat.pr[!is.na(dat.pr$ResponseId),]


##############################
# Analysis 
##############################
# calculate AMCEs

amce.all <- cj(dat, f1,  id = ~ ResponseId, estimate = "amce")
amce.cdu <- cj(dat.cdu, f1,  id = ~ ResponseId, estimate = "amce")
amce.spd <- cj(dat.spd, f1,  id = ~ ResponseId, estimate = "amce")
amce.fdp <- cj(dat.fdp, f1,  id = ~ ResponseId, estimate = "amce")
amce.b90 <- cj(dat.b90, f1,  id = ~ ResponseId, estimate = "amce")
amce.linke <- cj(dat.linke, f1,  id = ~ ResponseId, estimate = "amce")
amce.pr <- cj(dat.pr, f1,  id = ~ ResponseId, estimate = "amce")

# calculate MMs
mm.all <- cj(dat, f1,  id = ~ ResponseId, estimate = "mm")
mm.cdu <- cj(dat.cdu, f1,  id = ~ ResponseId, estimate = "mm")
mm.spd <- cj(dat.spd, f1,  id = ~ ResponseId, estimate = "mm")
mm.fdp <- cj(dat.fdp, f1,  id = ~ ResponseId, estimate = "mm")
mm.b90 <- cj(dat.b90, f1,  id = ~ ResponseId, estimate = "mm")
mm.linke <- cj(dat.linke, f1,  id = ~ ResponseId, estimate = "mm")
mm.pr <- cj(dat.pr, f1,  id = ~ ResponseId, estimate = "mm")

# Test for satisficing 
dat$Profile <- as.factor(dat$Profile)
dat.prof <- cj(dat, f1 ,id = ~ ResponseId,   estimate = "mm"
               , by =  ~Profile)

# Test for fatigue
dat$TaskID <- as.factor(dat$TaskID)
dat.task <- cj(dat, f1 ,id = ~ ResponseId,   estimate = "mm"
               , by =  ~TaskID)



#################################
# Create Data.Frames for Plotting
#################################
# satisficing test
plotData.1 <- data.frame(
  rbind(cbind(dat.prof[, -12], Type = "Profile", Number = dat.prof[,12]),
        cbind(dat.task[, -12], Type = "Task Number", Number = dat.task[,12])
  )
)
# substantive analysis
plotData.2 <- data.frame(
  rbind(cbind(amce.cdu, Party = "CDU"),
        cbind(amce.spd, Party = "SPD"),
        cbind(amce.spd, Party = "FDP"),
        cbind(amce.b90, Party = "B90/Gr"),
        cbind(amce.linke, Party = "LINKE"),
        cbind(mm.all, Party = "All"),
        cbind(amce.all, Party = "All"),
        cbind(mm.cdu, Party = "CDU"),
        cbind(mm.spd, Party = "SPD"),
        cbind(mm.spd, Party = "FDP"),
        cbind(mm.b90, Party = "B90/Gr"),
        cbind(mm.linke, Party = "LINKE"),
        cbind(amce.pr, Party = "PR Parties"),
        cbind(mm.pr, Party = "PR Parties")
        
  )
)

#################################
# Plotting Data
#################################
library(ggplot2)

# facet panel labeling
plotData.1$labels <- ""
plotData.1$labels[plotData.1$feature == "cj_age"] <- "Age"
plotData.1$labels[plotData.1$feature == "cj_sex"] <- "Gender"
plotData.1$labels[plotData.1$feature == "cj_ideo"] <- "Ideological\nPosition"
plotData.1$labels[plotData.1$feature == "cj_born"] <- "Place of\nBirth"
plotData.1$labels[plotData.1$feature == "cj_interest"] <- "Represents\nInterests of"
plotData.1$labels[plotData.1$feature == "cj_loyalty"] <- "Deviation\nfrom Party"
plotData.1$labels[plotData.1$feature == "cj_wk"] <- "District\nNomination"
plotData.1$labels[plotData.1$feature == "cj_tenure"] <- "Tenure"

plotData.1$level2 <- as.character(plotData.1$level)
plotData.1$level2[plotData.1$level == "Respondent's Local Party Chapter"] <- "R's Local Party Chapter"
plotData.1$level2[plotData.1$level == "Other Local Chapters in Respondent's PR District"] <- "Other Local Chapters in R's PR District"
plotData.1$level2[plotData.1$level == "Local Chapters outside Respondent's PR District"] <- "Local Chapters outside R's PR District"
plotData.1$level2[plotData.1$level == "Outside Respondent's PR District"] <- "Outside R's PR District"
plotData.1$level2[plotData.1$level == "In the area of the Respondent's Local Chapter"] <- "In the area of the R's Local Chapter"
plotData.1$level2[plotData.1$level == "in Respondent's PR District"] <- "in R's PR District"

#################################
# Figure 6 in Appendix: Satisficing and Fatigue
#################################
p1 = ggplot(plotData.1)
p1 = p1 + geom_pointrange(aes(x = as.factor(level2), y = estimate, 
                            ymin = lower, ymax = upper,group = Number, shape = Number), 
                        position = position_dodge(width = 1),
                        size = 0.5)  
p1 = p1 + geom_hline(aes(yintercept = 0.5), linetype = 2)
p1 = p1 + facet_grid(labels ~ Type, scales = "free") + xlab("") + ylab("Marginal Means")#+ ylab("Marginal Means") 
p1 = p1 + coord_flip() + theme(axis.text = element_text(size = rel(0.8)),
                             axis.ticks = element_line(colour = "black"),
                             legend.key = element_rect(fill = "white"),
                             plot.margin = unit(c(0, 0, 0, 0), "cm"),
                             legend.position="bottom",
                             panel.background = element_rect(fill = "white", colour = NA),
                             panel.border = element_rect(fill = NA, colour = "grey50"),
                             panel.grid.major = element_line(colour = "grey90", size = 0.2),
                             panel.grid.minor = element_line(colour = "grey98", size = 0.5),
                             strip.background = element_rect(fill = "white", colour = "grey50"),
                             strip.text.x = element_text(size = 10, colour = "black", face = "bold"),
                             strip.text.y = element_text(size = 8, colour = "black", face = "bold"))   


cat("create Figure 6\n")
p1

###--------------------------###



#################################
# Figure 2 in maintext: Delegates' Preferences
#################################

# plotting effects
plotData.2$labels <- ""
plotData.2$labels[plotData.2$feature == "cj_age"] <- "Age"
plotData.2$labels[plotData.2$feature == "cj_sex"] <- "Gender"
plotData.2$labels[plotData.2$feature == "cj_ideo"] <- "Ideological\nPosition"
plotData.2$labels[plotData.2$feature == "cj_born"] <- "Place of\nBirth"
plotData.2$labels[plotData.2$feature == "cj_interest"] <- "Represents\nInterests of"
plotData.2$labels[plotData.2$feature == "cj_loyalty"] <- "Deviation\nfrom Party"
plotData.2$labels[plotData.2$feature == "cj_wk"] <- "District\nNomination"
plotData.2$labels[plotData.2$feature == "cj_tenure"] <- "Tenure"

plotData.2$level2 <- as.character(plotData.2$level)
plotData.2$level2[plotData.2$level == "Respondent's Local Party Chapter"] <- "R's Local Party Chapter"
plotData.2$level2[plotData.2$level == "Other Local Chapters in Respondent's PR District"] <- "Other Local Chapters in R's PR District"
plotData.2$level2[plotData.2$level == "Local Chapters outside Respondent's PR District"] <- "Local Chapters outside R's PR District"
plotData.2$level2[plotData.2$level == "Outside Respondent's PR District"] <- "Outside R's PR District"
plotData.2$level2[plotData.2$level == "In the area of the Respondent's Local Chapter"] <- "In the area of the R's Local Chapter"
plotData.2$level2[plotData.2$level == "in Respondent's PR District"] <- "in R's PR District"

# plotting effects
p2 = ggplot(plotData.2[plotData.2$Party %in% c("All","PR Parties") & plotData.2$statistic == "mm" & plotData.2$feature %in% c("cj_interest"),])
p2 = p2 + geom_pointrange(aes(x = as.factor(level2), y = estimate, 
                            ymin = lower, ymax = upper), 
                        position = position_dodge(width = 1),
                        size = 0.5)
p2 = p2 + geom_hline(aes(yintercept = 0.5), linetype = 2)
p2 = p2 + facet_grid(labels ~ Party, scales = "free") + xlab("") + ylab("Marginal Means")#+ ylab("Marginal Means") 
p2 = p2 + coord_flip() + theme(axis.text = element_text(size = rel(0.8)),
                             axis.ticks = element_line(colour = "black"),
                             legend.key = element_rect(fill = "white"),
                             plot.margin = unit(c(0, 0, 0, 0), "cm"),
                             legend.position="bottom",
                             panel.background = element_rect(fill = "white", colour = NA),
                             panel.border = element_rect(fill = NA, colour = "grey50"),
                             panel.grid.major = element_line(colour = "grey90", size = 0.2),
                             panel.grid.minor = element_line(colour = "grey98", size = 0.5),
                             strip.background = element_rect(fill = "white", colour = "grey50"),
                             strip.text.x = element_text(size = 12, colour = "black", face = "bold"),
                             strip.text.y = element_text(size = 12, colour = "black", face = "bold"))   
cat("create Figure 2\n")
p2

 
###--------------------------###

#################################
# Figure 7 in the Appendix: Delegates' Preferences (Full)
#################################
 
p3 = ggplot(plotData.2[plotData.2$Party %in% c("All","PR Parties") & plotData.2$statistic == "mm",])
p3 = p3 + geom_pointrange(aes(x = as.factor(level2), y = estimate, 
                            ymin = lower, ymax = upper), 
                        position = position_dodge(width = 1),
                        size = 0.5)  
p3 = p3 + geom_hline(aes(yintercept = 0.5), linetype = 2)
p3 = p3 + facet_grid(labels ~ Party, scales = "free") + xlab("") + ylab("Marginal Means")#+ ylab("Marginal Means") 
p3 = p3 + coord_flip() + theme(axis.text = element_text(size = rel(0.8)),
                             axis.ticks = element_line(colour = "black"),
                             legend.key = element_rect(fill = "white"),
                             plot.margin = unit(c(0, 0, 0, 0), "cm"),
                             legend.position="bottom",
                             panel.background = element_rect(fill = "white", colour = NA),
                             panel.border = element_rect(fill = NA, colour = "grey50"),
                             panel.grid.major = element_line(colour = "grey90", size = 0.2),
                             panel.grid.minor = element_line(colour = "grey98", size = 0.5),
                             strip.background = element_rect(fill = "white", colour = "grey50"),
                             strip.text.x = element_text(size = 10, colour = "black", face = "bold"),
                             strip.text.y = element_text(size = 8, colour = "black", face = "bold"))   

cat("create Figure 7\n")
p3

###--------------------------###

#################################
# Figure 8 in the Appendix: Delegates' Preferences (by Party)
#################################

p4 = ggplot(plotData.2[!plotData.2$Party %in% c("All","PR Parties") & plotData.2$statistic == "mm",])
p4 = p4 + geom_pointrange(aes(x = as.factor(level2), y = estimate, 
                            ymin = lower, ymax = upper), 
                        position = position_dodge(width = 1),
                        size = 0.5)  
p4 = p4 + geom_hline(aes(yintercept = 0.5), linetype = 2)
p4 = p4 + facet_grid(labels ~ Party, scales = "free") + xlab("") + ylab("Marginal Means")#+ ylab("Marginal Means") 
p4 = p4 + coord_flip() + theme(axis.text = element_text(size = rel(0.8)),
                             axis.ticks = element_line(colour = "black"),
                             legend.key = element_rect(fill = "white"),
                             plot.margin = unit(c(0, 0, 0, 0), "cm"),
                             legend.position="bottom",
                             panel.background = element_rect(fill = "white", colour = NA),
                             panel.border = element_rect(fill = NA, colour = "grey50"),
                             panel.grid.major = element_line(colour = "grey90", size = 0.2),
                             panel.grid.minor = element_line(colour = "grey98", size = 0.5),
                             strip.background = element_rect(fill = "white", colour = "grey50"),
                             strip.text.x = element_text(size = 10, colour = "black", face = "bold"),
                             strip.text.y = element_text(size = 8, colour = "black", face = "bold"))   
cat("create Figure 8\n")
p4

###--------------------------###

##############################
# Analyses of interactions
##############################
# Ideological Proximity and Preference for Geographic Representation
f2 <-  choice ~ cj_age + cj_sex + cj_wk + cj_same_ideology + cj_born  + 
  cj_tenure + cj_loyalty

f3 <-  choice ~ cj_age + cj_sex + cj_wk + cj_ideo + cj_born  + 
  cj_tenure + cj_loyalty


mm.same.all <- cj(dat, f2,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")
mm.loyalty.all <- cj(dat, f3,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")

mm.same.cdu <- cj(dat.cdu, f2,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")
mm.loyalty.cdu <- cj(dat.cdu, f3,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")

mm.same.spd <- cj(dat.spd, f2,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")
mm.loyalty.spd <- cj(dat.spd, f3,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")

mm.same.fdp <- cj(dat.fdp, f2,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")
mm.loyalty.fdp <- cj(dat.fdp, f3,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")

mm.same.b90 <- cj(dat.b90, f2,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")
mm.loyalty.b90 <- cj(dat.b90, f3,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")

mm.same.linke <- cj(dat.linke, f2,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")
mm.loyalty.linke <- cj(dat.linke, f3,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")

mm.same.pr <- cj(dat.pr, f2,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")
mm.loyalty.pr <- cj(dat.pr, f3,  id = ~ ResponseId, by = ~ cj_interest, estimate = "mm")


#################################
# Create Data.Frames for Plotting
#################################

# substantive analysis
plotData.3 <- data.frame(
  rbind(cbind(mm.same.all, Party = "All"),
        cbind(mm.same.cdu, Party = "CDU"),
        cbind(mm.same.spd, Party = "SPD"),
        cbind(mm.same.fdp, Party = "FDP"),
        cbind(mm.same.b90, Party = "B90/Gr"),
        cbind(mm.same.linke, Party = "LINKE"),
        cbind(mm.same.pr, Party = "PR Parties")
        
  )
)

plotData.4 <- data.frame(
  rbind(cbind(mm.loyalty.all, Party = "All"),
        cbind(mm.loyalty.cdu, Party = "CDU"),
        cbind(mm.loyalty.spd, Party = "SPD"),
        cbind(mm.loyalty.fdp, Party = "FDP"),
        cbind(mm.loyalty.b90, Party = "B90/Gr"),
        cbind(mm.loyalty.linke, Party = "LINKE"),
        cbind(mm.loyalty.pr, Party = "PR Parties")
        
  )
)
# Level Names
plotData.3$labels <- ""
plotData.3$labels[plotData.3$feature == "cj_age"] <- "Age"
plotData.3$labels[plotData.3$feature == "cj_sex"] <- "Gender"
plotData.3$labels[plotData.3$feature == "cj_same_ideology"] <- "Ideological\nPosition"
plotData.3$labels[plotData.3$feature == "cj_born"] <- "Place of\nBirth"
plotData.3$labels[plotData.3$feature == "cj_interest"] <- "Represents\nInterests of"
plotData.3$labels[plotData.3$feature == "cj_loyalty"] <- "Deviation\nfrom Party"
plotData.3$labels[plotData.3$feature == "cj_wk"] <- "District\nNomination"
plotData.3$labels[plotData.3$feature == "cj_tenure"] <- "Tenure"

plotData.4$labels <- ""
plotData.4$labels[plotData.4$feature == "cj_age"] <- "Age"
plotData.4$labels[plotData.4$feature == "cj_sex"] <- "Gender"
plotData.4$labels[plotData.4$feature == "cj_ideo"] <- "Ideological\nPosition"
plotData.4$labels[plotData.4$feature == "cj_born"] <- "Place of\nBirth"
plotData.4$labels[plotData.4$feature == "cj_interest"] <- "Represents\nInterests of"
plotData.4$labels[plotData.4$feature == "cj_loyalty"] <- "Deviation\nfrom Party"
plotData.4$labels[plotData.4$feature == "cj_wk"] <- "District\nNomination"
plotData.4$labels[plotData.4$feature == "cj_tenure"] <- "Tenure"

plotData.3$level2 <- as.character(plotData.3$level)
plotData.3$level2[plotData.3$level == "Outside Respondent's PR District"] <- "Outside R's PR District"
plotData.3$level2[plotData.3$level == "In the area of the Respondent's Local Chapter"] <- "In the area of the R's Local Chapter"
plotData.3$level2[plotData.3$level == "in Respondent's PR District"] <- "in R's PR District"
plotData.3$level2[plotData.3$level == 0] <- "Ideologically Distant from R"
plotData.3$level2[plotData.3$level == 1] <- "Ideologically Close to R"


plotData.3$cj_interest2[plotData.3$cj_interest == "Respondent's Local Party Chapter"] <- "R's Local\nParty Chapter"
plotData.3$cj_interest2[plotData.3$cj_interest == "Other Local Chapters in Respondent's PR District"] <- "Other Local Chapters\nin R's PR District"
plotData.3$cj_interest2[plotData.3$cj_interest == "Local Chapters outside Respondent's PR District"] <- "Local Chapters outside \nR's PR District"

#################################
# Figure 9 in the Appendix: Interactions (Full)
#################################


p5 = ggplot(plotData.3[plotData.3$Party %in% c("All") & plotData.3$statistic == "mm" ,])
p5 = p5 + geom_pointrange(aes(x = as.factor(level2), y = estimate, 
                            ymin = lower, ymax = upper), 
                        position = position_dodge(width = 1),
                        size = 0.5)  
p5 = p5 + geom_hline(aes(yintercept = 0.5), linetype = 2)
p5 = p5 + facet_grid(labels ~ cj_interest2, scales = "free") + xlab("") + ylab("Marginal Means")#+ ylab("Marginal Means") 
p5 = p5 + coord_flip() + theme(axis.text = element_text(size = rel(1), colour = "black"),
                             axis.ticks = element_line(colour = "black"),
                             legend.key = element_rect(fill = "white"),
                             plot.margin = unit(c(0, 0, 0, 0), "cm"),
                             legend.position="bottom",
                             panel.background = element_rect(fill = "white", colour = NA),
                             panel.border = element_rect(fill = NA, colour = "grey50"),
                             panel.grid.major = element_line(colour = "grey90", size = 0.2),
                             panel.grid.minor = element_line(colour = "grey98", size = 0.5),
                             strip.background = element_rect(fill = "white", colour = "grey50"),
                             strip.text.x = element_text(size = 10, colour = "black", face = "bold"),
                             strip.text.y = element_text(size = 12, colour = "black", face = "bold")) 

cat("create Figure 9\n")
p5
 
###--------------------------###


#################################
# Figure 3 in main text: Interactions 
#################################

plotData.5 <- plotData.3[plotData.3$feature %in% c("cj_same_ideology", "cj_loyalty") ,]
plotData.5$level3 <- factor(plotData.5$level2, levels = c("Ideologically Close to R","Ideologically Distant from R",
                                                             "Rarely", "Sometimes","Often" ))
  
p6 = ggplot(plotData.5[plotData.5$Party %in% c("All") & plotData.5$statistic == "mm"& plotData.5$feature %in% c("cj_same_ideology", "cj_loyalty") ,])
p6 = p6 + geom_pointrange(aes(x = as.factor(level3), y = estimate, 
                            ymin = lower, ymax = upper), 
                        position = position_dodge(width = 1),
                        size = 0.5)  
p6 = p6 + geom_hline(aes(yintercept = 0.5), linetype = 2)
p6 = p6 + facet_grid(labels ~ cj_interest2, scales = "free") + xlab("") + ylab("Marginal Means")#+ ylab("Marginal Means") 
p6 = p6 + coord_flip() + theme(axis.text = element_text(size = rel(1), colour = "black"),
                             axis.ticks = element_line(colour = "black"),
                             legend.key = element_rect(fill = "white"),
                             plot.margin = unit(c(0, 0, 0, 0), "cm"),
                             legend.position="bottom",
                             panel.background = element_rect(fill = "white", colour = NA),
                             panel.border = element_rect(fill = NA, colour = "grey50"),
                             panel.grid.major = element_line(colour = "grey90", size = 0.2),
                             panel.grid.minor = element_line(colour = "grey98", size = 0.5),
                             strip.background = element_rect(fill = "white", colour = "grey50"),
                             strip.text.x = element_text(size = 10, colour = "black", face = "bold"),
                             strip.text.y = element_text(size = 12, colour = "black", face = "bold"))   
cat("create Figure 3\n")
p6

cat("end logging")
sink()